const fs = require("fs");
const http = require("http");
const urls = require("url");
const deletes = require("./delete.js")
const server = http.createServer((req, res) => {
    res.setHeader("Content-Type", "text/html;charset=utf-8");


    let pathObj = urls.parse(req.url, true);
    let query = pathObj.query;
    let url;
    // if(query.path)
    // 安全的判断
    // 判断是否有path参数 ，做文件夹显示
    if (typeof query.path != "undefined") {
        url = query.path;
    } else {
        url = "../../../dailywork";
    }

    if (typeof query.del != "undefined") {
        let delpath = query.del;
        let stat = fs.statSync(delpath);
        
        if (stat.isDirectory()) { 
            deletes.removeDir(delpath)
        } else {
            fs.unlinkSync(delpath)
        }
        res.statusCode = 302;
        res.setHeader("loction","/")
    }

    let arr = fs.readdirSync(url)
    let str = `<table><tr><th>文件名</th><th>操作</th></tr>`;
    arr.forEach((item) => {
        let mypath = url + "/" + item;
        let stat = fs.statSync(mypath);
        if (stat.isDirectory()) {
            str += `<tr><td><a href="/?path=${mypath}">${item}</a></td><td><a href="/?del=${mypath}">删除</a></td></tr>`
        } else {
            str += `<tr><td>${item}</td><td><a href="/?del=${mypath}">删除</a></td></tr>`
        }

    })
    str += "</table>";
    res.write(str);
    res.end();

    // let wenjian = document.querySelector(".wenjian");
    // wenjian.onclick = function () {

    // }
})
server.listen(8585);
